package ru.kreda.webapp.client.ui;

import com.google.gwt.event.logical.shared.ResizeEvent;
import com.google.gwt.event.logical.shared.ResizeHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.HasHorizontalAlignment;
import com.google.gwt.user.client.ui.HasVerticalAlignment;
import com.google.gwt.user.client.ui.HorizontalPanel;
import com.google.gwt.user.client.ui.Image;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.VerticalPanel;

public class BusyPanel extends PopupPanel implements ResizeHandler {
	private static BusyPanel INSTANCE = null;
	private Image image = new Image("resources/images/default/shared/blue-loading.gif");
	private HTML header = new HTML();

	private BusyPanel() {
		super(false);
		setGlassEnabled(true);
		HorizontalPanel panel = new HorizontalPanel();
		panel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		panel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);

		VerticalPanel imagePanel = new VerticalPanel();
		imagePanel.setStyleName("loading");
		imagePanel.setHorizontalAlignment(HasHorizontalAlignment.ALIGN_CENTER);
		imagePanel.setVerticalAlignment(HasVerticalAlignment.ALIGN_MIDDLE);

		imagePanel.add(header);
		imagePanel.add(image);

		panel.add(imagePanel);

		add(panel);

		Window.addResizeHandler(this);
	}

	public static BusyPanel getInstance() {
		if (INSTANCE == null) {
			INSTANCE = new BusyPanel();
		}
		return INSTANCE;
	}

	@Override
	public void onResize(ResizeEvent event) {
		setPixelSize(event.getWidth(), event.getHeight());
	}

	@Override
	public void show() {
		setPixelSize(Window.getClientWidth(), Window.getClientHeight());
		super.show();
	}

	public void showBusy(String message) {
		header.setHTML("<h1><span>" + message + "</span></h1>");
		if (!image.isVisible()) {
			image.setVisible(true);
		}
		center();
	}

	public void hideBusy() {
		hide();
	}

}
